<?php

namespace App\ServicesNew\Impl;

use App\Entities\CleanStockConfigModel;
use App\Entities\ProductSkuEntity;
use App\Meta\OrderPeriodDate;
use App\Services\CitySettingsService;
use App\ServicesNew\OrderService;
use App\ServicesNew\StockService;
use Illuminate\Support\Facades\Log;

class StockServiceImpl implements StockService
{
    /**
     * @var OrderService
     */
    protected $orderService;

    /**
     * @var CitySettingsService
     */
    protected $citySettingsService;

    public function __construct(OrderService $orderService, CitySettingsService $citySettingsService)
    {
        $this->orderService = $orderService;
        $this->citySettingsService = $citySettingsService;

    }

    /**
     * @inheritDoc
     */
    public function getLastServiceAbleDateTime(int $cityId, int $productId)
    {
        $cleanNum = $this->getCityStockNum($cityId, $productId);

        $returnArr = [];
        for ($i = 0; $i <= 10; $i++) {
            if ($i == 0) {
                $dayStr = date('Y-m-d');
            } else {
                $dayStr = date('Y-m-d', strtotime("+{$i} day"));
            }

            if (!$this->citySettingsService->weekDayAvailable($cityId, strtotime($dayStr))) {
                continue;
            }

            $period = $this->citySettingsService->buildCityTimePeriods($cityId, true);
            $period = $this->citySettingsService->filterReservHours($cityId, $period, strtotime($dayStr)); // 过滤

            foreach ($period as $timeperiodId => $timeperiodName) {
                $count = $this->orderService->getOrderPeriodCount($cityId, $productId, $dayStr, $timeperiodId);
                if ($cleanNum > $count) {
                    $returnArr = ['id' => $timeperiodId, 'time' => $timeperiodName, 'day' => $dayStr];
                    break 2;
                }
            }
        }

        $orderPeriodDate = new OrderPeriodDate();
        if (!empty($returnArr)) {
            $orderPeriodDate->setDate($dayStr);
            $orderPeriodDate->setTimePeriodDesc($returnArr['time'] ?? '');
            $orderPeriodDate->setTimePeriodId($returnArr['id'] ?? 0);
        }
        return $orderPeriodDate;
    }

    /**
     * @inheritDoc
     */
    public function getLastServiceAbleDateTimeByProductSkuEntity(ProductSkuEntity $productSkuEntity)
    {
        return $this->getLastServiceAbleDateTime($productSkuEntity->getCityId(), $productSkuEntity->getProductId());
    }

    /**
     * 查询城市库存配置
     * @param int $productId
     * @return CleanStockConfigModel
     */
    private function getDefaultStockConfig(int $productId)
    {
        return $this->getCityStockConfig(0, $productId);
    }

    /**
     * 查询城市库存配置
     * @param int $cityId
     * @param int $productId
     * @return CleanStockConfigModel
     */
    private function getCityStockConfig(int $cityId, int $productId)
    {
        return CleanStockConfigModel::where('city_id', $cityId)
            ->where('products_id', $productId)
            ->where('status', 1) // 开启状态
            ->first();
    }

    /**
     * @inheritDoc
     */
    public function getTimePeriodArr(string $date, int $cityId, int $productId)
    {
        if (!$this->citySettingsService->weekDayAvailable($cityId, strtotime($date))) {
            return [];
        }

        $period = $this->citySettingsService->buildCityTimePeriods($cityId, true);
        $period = $this->citySettingsService->filterReservHours($cityId, $period, strtotime($date)); // 过滤数小时内不可预约
        $period = $this->citySettingsService->filterBusyPeriods($cityId, $period); //过滤忙时时段

        $cleanNum = $this->getCityStockNum($cityId, $productId);

        $returnArr = [];
        foreach ($period as $timeperiodId => $timeperiodName) {
            $count = $this->orderService->getOrderPeriodCount($cityId, $productId, $date, $timeperiodId);
            if ($cleanNum <= $count) {
                $returnArr[] = ['id' => $timeperiodId, 'time' => $timeperiodName, 'couldOrder' => 0];
            } else {
                $returnArr[] = ['id' => $timeperiodId, 'time' => $timeperiodName, 'couldOrder' => 1];
            }
        }
        return $returnArr;
    }

    /**
     * 库存数
     * @param int $cityId
     * @param int $productId
     * @return int
     */
    private function getCityStockNum(int $cityId, int $productId)
    {
        if ($cityId != 0) {
            $cleanStockConfig = $this->getCityStockConfig($cityId, $productId);
            if (is_null($cleanStockConfig)) { // 默认全局配置
                $cleanStockConfig = $this->getDefaultStockConfig($productId);
            }
        } else {
            $cleanStockConfig = $this->getDefaultStockConfig($productId);
        }

        if (is_null($cleanStockConfig)) {  // 没有对应城市配置记录
            // 没有配置，不设限
            $cleanNum = 999;
            Log::info('城市库存读取 自定义值 0 ' . $productId . ' 999');
        } else {
            $cleanNum = $cleanStockConfig->clean_num;
            if ($cleanNum < 0) {
                $cleanNum = 999;
            }
        }

        return $cleanNum;
    }
}
